<template>
	<view class="content">

		<view class="add">

			<view class="s1">STEP 1/4</view>
			<view class="title">基本信息</view>

			<view class="c1">活动名称</view>
			<view class="c2">
				<u--input v-model='row.title' placeholder="请输入" :customStyle="{padding: '0 32rpx'}" :maxlength="24">
				</u--input>
			</view>

			<view class="c1">活动开始时间</view>
			<view class="c2">
				<u--input v-model='row.start_time' placeholder="请选择" :customStyle="{padding: '0 32rpx'}"
					suffixIcon="arrow-down" suffixIconStyle="color: #7D8592" readonly>
				</u--input>
				<view class="on_in" @click="start_show = true"></view>
			</view>

			<view class="c1">活动结束时间</view>
			<view class="c2">
				<u--input v-model='row.end_time' placeholder="请选择" :customStyle="{padding: '0 32rpx'}"
					suffixIcon="arrow-down" suffixIconStyle="color: #7D8592" readonly>
				</u--input>
				<view class="on_in" @click="end_show = true"></view>
			</view>

			<view class="c1">联系方式</view>
			<view class="c2">
				<u--input v-model='row.phone' placeholder="请输入" :customStyle="{padding: '0 32rpx'}">
				</u--input>
			</view>

			<view class="c1">活动地址</view>
			<view class="c2">
				<u--input v-model='row.address' placeholder="请输入" :customStyle="{padding: '0 32rpx'}">
				</u--input>
			</view>

			<view class="c1">活动价格</view>
			<view class="c2">
				<u--input v-model='row.money' type='number' placeholder="请输入" :customStyle="{padding: '0 32rpx'}">
				</u--input>
			</view>

			<view class="c1">活动标题图</view>
			<view class="c3">(推荐宽高比2:1， 文件大小不超过6M)</view>
			<view class="c2 c2-1">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @beforeRead="beforeRead" @delete="deletePic"
					name="1" :useBeforeRead="true" :maxCount="1" :maxSize='1024 * 1024 * 6' uploadIcon='plus'
					uploadIconColor='#D8D8D8'></u-upload>
			</view>

		</view>

		<view class="but">
			<view @click="save" class="save">保存</view>
			<view class="s2" @click="onSend()">
				<text>下一步</text>
				<u-icon name="arrow-rightward" color='#fff'></u-icon>
			</view>
		</view>

		<u-datetime-picker :show="start_show" v-model="start_time" mode="datetime" :formatter="formatter"
			:minDate="minDete" @close='onClose' @confirm='onConfirmStart' @cancel='onClose'
			closeOnClickOverlay></u-datetime-picker>

		<u-datetime-picker :show="end_show" v-model="end_time" mode="datetime" :formatter="formatter" :minDate="minDete"
			@close='onClose' @confirm='onConfirmEnd' @cancel='onClose' closeOnClickOverlay></u-datetime-picker>

		<address-picker :show="addressShow" closeOnClickOverlay @confirm='confirmAddress' @cancel='addressShow=false'
			@close='addressShow = false' :address-data="addressData" :indexs="indexs" :areaId="areaId"
			:type="type"></address-picker>

		<u-toast ref="uToast"></u-toast>
		<u-overlay :show="show" @click="show = false">
			<view class="modal">
				<view class="box" @click.stop>
					<view class="title">
						是否需要为你创建的内容进行保存
						避免下次进入重新创建
					</view>
					<view class="btn">
						<view class="out" @click="handleSave(0)">
							直接退出
						</view>
						<view class="in" @click="handleSave(1)">
							保存
						</view>
					</view>
				</view>
			</view>
		</u-overlay>
	</view>
</template>

<script>
	import conf from '@/common/config.js';
	export default {
		props: {
			addForm: {
				type: Object,
				default: () => {
					return {}
				}
			},
			editId: {
				type: [Number, String]
			}
		},
		data() {
			return {
				show: false,
				id: 0,
				start_show: false,
				start_time: Number(new Date()),
				end_show: false,
				end_time: Number(new Date()),
				minDete: 0,
				fileList1: [],
				row: {
					title: '',
					start_time: '',
					end_time: '',
					phone: '',
					address: '',
					money: '',
					fullurl: ''
				},


				addressShow: false,
				indexs: [0, 0, 0],
				areaId: [1, 110000, 110101],
				addressData: ['北京市', '北京市', '东城区'],
				type: 3, //1-省，2-省市，3-省市区
			};
		},
		mounted() {
			if (Object.keys(this.addForm).length) {
				this.row = this.addForm
				if (typeof this.addForm.end_time == 'number') {
					if (this.addForm.end_time) {
						this.row.end_time = uni.$u.timeFormat(this.addForm.end_time * 1000, 'yyyy-mm-dd hh:MM')
					}
					if (this.addForm.start_time) {
						this.row.start_time = uni.$u.timeFormat(this.addForm.start_time * 1000, 'yyyy-mm-dd hh:MM')
					}
				}
				if (this.addForm.start_time === 0) {
					this.addForm.start_time = ''
				}
				if (this.addForm.end_time === 0) {
					this.addForm.end_time = ''
				}
				this.$nextTick(() => {
					if (this.addForm.images) {
						this.fileList1 = [{
							url: this.addForm.images.startsWith('http') ? this.addForm.images : conf
								.preview_url + this.addForm.images,
							path: this.addForm.images
						}]
					}

				})
			}
			this.minDete = Number(new Date());
		},
		// onShow() {
		// 	if (this.id > 0) {
		// 		this.getInfo();
		// 	}
		// },
		methods: {
			save() {
				this.show = true
			},
			handleSave(type) {
				if (type) {
					const params = Object.keys(this.addForm).length ? this.addForm : this.row
					this.$API.saveDraft({
						title: params.title,
						start_time: params.start_time,
						end_time: params.end_time,
						phone: params.phone,
						address: params.address,
						images: this.fileList1.length ? this.fileList1[0].url.startsWith('http') ? this.fileList1[
							0].path : this.fileList1[0].url : '',
						money: params.money,
					}, +this.editId).then(res => {
						this.show = false
						uni.showModal({
							title: '提示',
							content: '恭喜您保存成功！',
							showCancel: false,
							success: () => {
								// this.$store.commit('$uStore', {
								// 	name: 'vuex_tempForm',
								// 	value: {}
								// })
								uni.redirectTo({
									url: '/pages/activity/index'
								})
							}
						})

					})
				} else {
					uni.navigateBack()
				}
			},
			getInfo() {
				this.$API.getActivity({
					id: this.id
				}).then(res => {
					this.row = {
						id: res.data.id,
						title: res.data.title,
						start_time: this.formatDate(res.data.start_time * 1000),
						end_time: this.formatDate(res.data.end_time * 1000),
						phone: res.data.phone,
						address: res.data.address,
						money: res.data.money,
						edit_status: res.data.edit_status
					}
					this.fileList1 = [];
					if (res.data.images != '') {
						res.data.images_url.forEach(v => {
							this.fileList1.push({
								url: v
							})
						});
					}

				})
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			formatDate(value) {
				if (value == undefined) {
					return;
				}
				// let date = new Date(value * 1000);
				let date = new Date(value);
				//时间戳为10位需*1000，时间戳为13位的话不需乘1000
				let y = date.getFullYear();
				let MM = date.getMonth() + 1;
				MM = MM < 10 ? ('0' + MM) : MM; //月补0
				let d = date.getDate();
				d = d < 10 ? ('0' + d) : d; //天补0
				let h = date.getHours();
				h = h < 10 ? ('0' + h) : h; //小时补0
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m; //分钟补0
				let s = date.getSeconds();
				s = s < 10 ? ('0' + s) : s; //秒补0
				return y + '-' + MM + '-' + d + ' ' + h + ':' + m; //年月日
				// return y + '-' + MM + '-' + d + ' ' + h + ':' + m+ ':' + s; //年月日时分秒
			},
			onClose() {
				this.start_show = false;
				this.end_show = false;
			},
			onConfirmStart(e) {
				this.row.start_time = this.formatDate(e.value);
				this.start_show = false;
			},
			onConfirmEnd(e) {
				this.row.end_time = this.formatDate(e.value);
				this.end_show = false;
			},
			confirmAddress(val) {
				console.log(val);
				this.row.address = val.value.join('')
				this.addressShow = false
			},
			// go() {
			// 	if (!this.row.title) return this.$u.toast('请先输入活动名称')
			// 	this.$u.route({
			// 		url: 'pages/activity/previewActivity',
			// 		params: {
			// 			title: this.row.title
			// 		}
			// 	})
			// },
			beforeRead(event) {
				console.log(event)
				const MAX_SIZE = 1024 * 1024 * 6; // 5MB
				if (event.file.size > MAX_SIZE) {
					this.$refs.uToast.show({
						type: 'error',
						message: "活动banner图不能超过6M",
					});
					return false;
				}
				return true;
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.row.images = ''
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				// console.log('lists', lists, this.fileList1)
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				let host_url = conf.url_config + '/api/common/upload';
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: host_url,
						filePath: url,
						name: 'file',
						formData: {
							size: '5'
						},
						header: {
							Token: this.vuex_token
						},
						success: (res) => {
							let data = JSON.parse(res.data);
							setTimeout(() => {
								this.row.fullurl = data.data.fullurl
								resolve(data.data.url)
							}, 1000)
						}
					});
				})
			},
			onSend() {
				if (!this.row.title) return this.$u.toast('活动名称不能为空')
				if (!this.row.start_time) return this.$u.toast("开始时间不能为空")
				if (!this.row.end_time) return this.$u.toast('结束时间不能为空')
				if (+new Date(this.row.end_time) <= (+new Date(this.row.start_time))) return this.$u.toast('开始时间不能大于结束时间')
				if (!this.row.phone) return this.$u.toast('联系方式不能为空')
				if (!uni.$u.test.mobile(this.row.phone)) return this.$u.toast('请输入正确的手机号')
				if (!this.row.address) return this.$u.toast('活动地址不能为空')
				// if (!this.row.money) return this.$u.toast('活动价格不能为空')
				if (!this.row.title) return this.$u.toast('活动名称不能为空')
				if (!this.fileList1.length) return this.$u.toast("活动banner不能为空")
				let that = this
				let data = this.row;

				data.image = [];
				console.log(this.fileList1);
				this.fileList1.forEach(v => {
					data.image.push(v.url.startsWith('http') ? v.path : v.url);
				});

				data.images = data.image.join(',')
				console.log(data);
				this.$emit('updateaddOne', data)
			}
		}
	}
</script>

<style lang="scss">
	.content {
		width: 670rpx;
		margin: 0 auto;
	}

	.add {
		width: 566rpx;
		padding: 52rpx;
		background-color: #fff;
		border-radius: 48rpx;
		margin-top: 52rpx;

		.s1 {
			width: 100%;
			height: 34rpx;
			font-size: 28rpx;
			font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
			font-weight: 600;
			color: #7677EB;
			line-height: 34rpx;
			text-align: center;
		}

		.title {
			width: 100%;
			height: 52rpx;
			font-size: 36rpx;
			font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
			font-weight: 600;
			color: #110202;
			line-height: 52rpx;
			text-align: center;
			margin-top: 16rpx;
		}

		.c1 {
			height: 28rpx;
			font-size: 28rpx;
			font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
			font-weight: 400;
			color: #7D8592;
			line-height: 28rpx;
			margin-top: 56rpx;
		}

		.c2 {
			width: 566rpx;
			margin-top: 40rpx;
			position: relative;

			/deep/ .u-input {
				height: 98rpx;
				border-radius: 28rpx;
			}

			/deep/ .u-upload {
				.u-upload__button {
					background-color: #fff;
					border: 2rpx solid #D8E0F0;
					border-radius: 16rpx;

					.u-icon__icon {
						span {
							font-size: 36rpx;
						}
					}
				}

				.u-upload__deletable {
					width: 24rpx;
					height: 24rpx;
					line-height: 24rpx;
					text-align: center;
					border-radius: 100%;
					background-color: #000000;

					&__icon {
						position: relative;
						inset: 0;
					}
				}
			}

			.on_in {
				position: absolute;
				inset: 0;
			}
		}

		.c3 {
			height: 36rpx;
			font-size: 24rpx;
			font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
			font-weight: 400;
			color: #9DA4B0;
			line-height: 36rpx;
			margin-top: 8rpx;
		}

		.c2-1 {
			margin-top: 16rpx;
		}
	}

	.but {
		@include flex;
		justify-content: space-between;
		margin-top: 60rpx;
		margin-bottom: 60rpx;

		.ss {
			width: 176rpx;
			height: 96rpx;
			line-height: 96rpx;
			text-align: center;
			box-shadow: 0rpx 12rpx 116rpx 0rpx rgba(196, 203, 214, 0.1036);
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			border: 2rpx solid #7677EB;
			font-weight: 400;
			font-size: 30rpx;
			color: #7677EB;
			box-sizing: border-box;
		}

		.save {
			width: 176rpx;
			height: 96rpx;
			box-shadow: 0rpx 12rpx 116rpx 0rpx rgba(196, 203, 214, 0.1036);
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			border: 2rpx solid #7677EB;
			font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
			font-weight: 400;
			font-size: 30rpx;
			color: #7677EB;
			text-align: center;
			line-height: 96rpx;
			box-sizing: border-box;
		}

		.s2 {
			width: 290rpx;
			height: 96rpx;
			background: #7677EB;
			box-shadow: 0 12rpx 24rpx 0 rgba(63, 140, 255, 0.2637);
			border-radius: 28rpx;
			@include flex;
			justify-content: center;

			text {
				font-size: 30rpx;
				font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
				font-weight: 400;
				color: #FFFFFF;
				line-height: 96rpx;
			}

			/deep/ .u-icon {
				margin-left: 28rpx;
			}
		}
	}

	.modal {

		display: flex;
		height: 100%;
		align-items: center;
		justify-content: center;
		padding: 0 40rpx;

		.box {
			width: 622rpx;
			height: 432rpx;
			background: #FFFFFF;
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			padding: 0 40rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.title {
				font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
				font-weight: 400;
				font-size: 32rpx;
				color: #000000;
				text-align: center;
				margin-top: 70rpx;
				padding: 0 30rpx;
			}

			.btn {
				margin-bottom: 70rpx;
				display: flex;
				justify-content: space-between;

				.out {
					width: 240rpx;
					height: 96rpx;
					box-shadow: 0rpx 12rpx 24rpx 0rpx rgba(63, 140, 255, 0.2637);
					border-radius: 28rpx 28rpx 28rpx 28rpx;
					border: 2rpx solid #7677EB;
					font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
					font-weight: 400;
					font-size: 30rpx;
					color: #7677EB;
					text-align: center;
					line-height: 96rpx;
					box-sizing: border-box;
				}

				.in {
					width: 240rpx;
					height: 96rpx;
					background: #7677EB;
					box-shadow: 0rpx 12rpx 24rpx 0rpx rgba(63, 140, 255, 0.2637);
					border-radius: 28rpx;
					font-family: Alibaba PuHuiTi 2.0, Alibaba PuHuiTi 20;
					font-weight: 400;
					font-size: 30rpx;
					color: #FFFFFF;
					text-align: center;
					line-height: 96rpx;
				}
			}
		}

	}
</style>